package cn.zhangjie.controller;

import cn.zhangjie.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/getById/{id}")
    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public User getById(@PathVariable("id") Long id){
        //1.发送http请求，可以使用http工具类
        //2.使用RestTemplate发送请求，必须加上http
        String url = "Http://user-server/user/getById/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    // 降级方法，参数和返回值必须和被熔断的方法一致 ，方法名要和fallbackMethod的值一致
    public User fallbackMethod(@PathVariable("id") Long id){
        return new User(-1l, "服务熔断触发", "用户服务不可用！");
    }
    /*
     * @Description: 配置负载均衡为随机算法
     * @Author: Director
     * @Date: 2022/7/27 17:00
     * @return: com.netflix.loadbalancer.RandomRule
     **/
    @Bean
    public RandomRule randomRule(){
        return new RandomRule();
    }

}
